<?php
/**
 * Created by PhpStorm.
 * User: zjw
 * Date: 2018/5/3
 * Time: 下午5:16
 */

namespace common\service;

use common\helpers\predis\Predis;
use common\jobs\NoticeApiJob;
use common\jobs\PromotionUserJob;
use common\jobs\SmsJob;
use common\jobs\UpdateCouponJob;

use common\models\Coupon;
use common\models\CouponCategory;

use common\models\User;
use common\models\UserCoupon;

use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
use yii;
use yii\mongodb\Database;

/**
 * Class UserService
 * @package common\service
 * @SuppressWarnings(PHPMD)
 */
class UserService
{
    /**
     * 获取所有优惠券  按分类获取
     * @return array
     */
    public function getCouponList()
    {
        /** @var Database $database */
        $database = Yii::$app->mongo->getDatabase("web");
        $collection = $database->getCollection("user_coupon");
        $userCouponList = $collection->find(['user_id' => intval(Yii::$app->user->id)], [], ['sort' => 1])->toArray();
        $couponService = ServiceFactory::getInstance()->getCouponService();
        $couponArr = [];
        if (count($userCouponList) > 0) {
            foreach ($userCouponList as $key => $userCoupon) {
                $coupon = $couponService->getCouponById($userCoupon['coupon_id']);
                if ($coupon != null) {
                    unset($coupon['id'], $coupon['_id'], $coupon['created_at'], $coupon['updated_at'], $coupon['origin_num'], $coupon['use_num']);
                    $category = ServiceFactory::getInstance()->getCouponCategoryService()->getCategory($coupon['catalog']);
                    $coupon['catalog_name'] = $category['name'];
                    $coupon['scene'] = $category['scene'];
                    $couponArr[$key] = $coupon;
                }
            }
        }
        return $couponArr;
    }

    public function getCouponListByCatalog($catalog)
    {
        /** @var Database $database */
        $database = Yii::$app->mongo->getDatabase("web");
        $collection = $database->getCollection("user_coupon");
        $userCouponList = $collection->find(['user_id' => intval(Yii::$app->user->id), 'catalog' => intval($catalog)], [], ['sort' => 1])->toArray();
        $couponService = ServiceFactory::getInstance()->getCouponService();
        $couponArr = [];
        if (count($userCouponList) > 0) {
            foreach ($userCouponList as $key => $userCoupon) {
                $coupon = $couponService->getCouponById($userCoupon['coupon_id']);
                if ($coupon != null) {
                    unset($coupon['id'], $coupon['_id'], $coupon['created_at'], $coupon['updated_at'], $coupon['origin_num'], $coupon['use_num']);
                    $category = ServiceFactory::getInstance()->getCouponCategoryService()->getCategory($coupon['catalog']);
                    $coupon['catalog_name'] = $category['name'];
                    $coupon['scene'] = $category['scene'];
                    $couponArr[$key] = $coupon;
                }
            }
        }
        return $couponArr;
    }


    /**
     *  是否已经领取过某分类优惠券
     * @return bool
     */
    public static function hasReward($catalogId)
    {
        /** @var Database $database */
        $database = Yii::$app->mongo->getDatabase("web");
        $couponCategoryCollection = $database->getCollection("coupon_category");
        $couponCategory = $couponCategoryCollection->findOne(['_id' => $catalogId]);
        $userCouponCollection = $database->getCollection("user_coupon");
        $userCoupon = $userCouponCollection->findOne(['user_id' => intval(Yii::$app->user->id), 'catalog' => intval($couponCategory['id'])]);
        if ($userCoupon) {
            return true;
        }
        return false;
    }

    /**
     * 分发优惠券 || 现金券
     * @param $couponCategory
     * @return array|null
     * @throws yii\base\Exception
     */
    public static function createUserCoupon($couponCategory, $userId)
    {
        /** @var Database $database */
        $database = Yii::$app->mongo->getDatabase();
        $coupon_collection = $database->getCollection("coupon");
        $user_coupon_collection = $database->getCollection("user_coupon");
        //一码多用
        if ($couponCategory['type'] == CouponCategory::TYPE_NUM_MANY) {
            $coupon = $coupon_collection->findOne(['catalog_mark_id' => $couponCategory['mark_id']]);
            if ($coupon['use_num'] >= $coupon['origin_num']) {
                CouponCategory::getCollection()->update(['mark_id' => $couponCategory['mark_id']], ['status' => CouponCategory::STATUS_OFF]);
                throw new yii\base\Exception($couponCategory['mark_id'] . "该优惠券已经领完了");
            }
            $user_coupon_collection->insert(['user_id' => intval($userId), 'catalog' => $coupon['catalog'], 'coupon_id' => $coupon['id'], 'mark_id' => $couponCategory['mark_id'], 'status' => UserCoupon::STATUS_OK, 'attempt' => 1, 'created_at' => time()]);
            $coupon_collection->update(['id' => $coupon['id']], ['use_num' => $coupon['use_num'] + 1]);
        } else {
            $coupon = $coupon_collection->findOne(['catalog_mark_id' => $couponCategory['mark_id'], 'status' => intval(Coupon::STATUS_VALID)]);
            if (empty($coupon)) {
                CouponCategory::getCollection()->update(['mark_id' => $couponCategory['mark_id']], ['status' => CouponCategory::STATUS_OFF]);
                throw new yii\base\Exception($couponCategory['mark_id'] . "该优惠券已经领完了");
            }
            $user_coupon_collection->insert(['user_id' => intval($userId), 'catalog' => $coupon['catalog'], 'coupon_id' => $coupon['id'], 'mark_id' => $couponCategory['mark_id'], 'status' => UserCoupon::STATUS_OK, 'attempt' => 1, 'created_at' => time()]);
            $coupon_collection->update(['id' => $coupon['id']], ['status' => Coupon::STATUS_INVALID]);
        }
        $user = User::findOne($userId);
        if (intval($couponCategory['group_id']) > 0) {
            //调用api 绑定手机号
            self::bindPhone($user->phone, $couponCategory['group_id']);
        }
        Yii::$app->queue->push(new UpdateCouponJob([
            'couponId' => $coupon['id'],
            'catalog' => $coupon['catalog'],
            'markId' => $couponCategory['mark_id'],
            'couponOriginId' => $coupon['origin_id'],
            'userId' => $userId,
            'couponType' => $couponCategory['type']
        ]));

        //todo  通知数据层
        Yii::$app->queue_notice_api->push(new NoticeApiJob([
            'phone' => $user->phone,
            'couponId' => $coupon['origin_id']
        ]));

        //如果有密码 短信通知卡号 密码
//        if (!empty($coupon['password'])) {
//            $dataVariables = [['Name' => 'CARD_MONEY', 'Value' => $coupon['discount_amount']], ['Name' => 'CARD_NO', 'Value' => $coupon['code']], ['Name' => 'CARD_PWD', 'Value' => $coupon['password']]];
//            Yii::$app->queue_sms->push(new SmsJob([
//                'phone' => $user->phone,
//                'dataVariables' => $dataVariables,
//                'template' => '000014'
//            ]));
//        }

        return $coupon;
    }


    public static function bindPhone($phone, $itemId)
    {
        $queueTempName = "queue_bind_phone_0";
        for ($i = 0; $i < 4; $i++) {
            $key = "queue_bind_phone_" . $i;

            $num = Predis::getInstance()->getClient()->client->get($key);
            if (empty($num)) {
                Predis::getInstance()->getClient()->client->set($key, 1);
            }
            $queueTempNum = Predis::getInstance()->getClient()->client->get($queueTempName);
            $queueNum = Predis::getInstance()->getClient()->client->get($key);
            if ($queueNum < $queueTempNum) {
                $queueTempName = $key;
            }
        }
        $queue = Yii::$app->{$queueTempName};
        $queue->push(new PromotionUserJob([
            'phoneNumberOrEmail' => $phone,
            'groupType' => $itemId
        ]));
        Predis::getInstance()->getClient()->client->incr($queueTempName);
        return true;
    }

    /**
     * 是否领取过某个奖池的奖品
     * @param $scene
     * @return bool
     */
    public static function hasRewardByScene($scene)
    {
        $booleanReward = false;
        $boxService = ServiceFactory::getInstance()->getBoxService();
        $box = $boxService->getBoxByScene($scene);
        $userCouponCollection = UserCoupon::getCollection();
        if (!empty($box)) {
            $categoryList = json_decode($box['content'], true);
            foreach ($categoryList as $key => $category) {
                $userCoupon = $userCouponCollection->findOne(['user_id' => intval(Yii::$app->user->id), 'catalog' => intval($category)]);
                if ($userCoupon) {
                    $booleanReward = true;
                    return $booleanReward;
                }
            }
        }
        return $booleanReward;
    }


    /**
     * [{"_id":"5bbca7e12536ea00086fefa2","id":1,"phone":"18814887805","customer_id":"18814887805","nickname":"nickname","avatar":"images/727dd9bc2672b273cec436e0749619e8.jpg","open_id":"18814887805","status":1,"created_at":1539090401,"updated_at":1539571126}]
     * @param $phone
     * @param $open_id
     * @param $customer_id
     * @return string
     * @throws \Exception
     */
    public function getUserByApi($phone, $open_id, $customer_id)
    {
        $baseUrl = getenv("ISSURE_COUPON_API");
        $url = $baseUrl . "api/user?phone=$phone&open_id=$open_id&customer_id=$customer_id";
        try {
            $result = HttpRequestService::sendGetRequest($url);
            if (!empty($result->data)) {
                return $result->data;
            }
            return '';
        } catch (\Exception $e) {
            throw $e;
        }
    }

    /**
     * {"code":-5,"msg":"用户已经存在","data":null}
     * {"code":1,"msg":"操作成功","data":{"_id":null,"id":34,"phone":"18814887000","customer_id":null,"nickname":null,"avatar":null,"open_id":null,"status":0,"created_at":1539842256,"updated_at":1539842256}}
     * @param $phone
     * @param $open_id
     * @param $customer_id
     * @return mixed
     * @throws \Exception
     */
    public function registerUser($phone, $open_id, $customer_id, $avatar, $nickname)
    {
        $data = ['phone' => $phone, 'open_id' => $open_id, 'customer_id' => $customer_id, 'avatar' => $avatar, 'nickname' => $nickname];
        $baseUrl = getenv("ISSURE_COUPON_API");
        $url = $baseUrl . "api/user";
        try {
            $result = HttpRequestService::sendRequest($url, "POST", $data);
            if ($result->code == 1) {
                $user = new User();
                $user->customer_id = $result->data->customer_id;
                $user->nickname = $result->data->nickname;
                $user->avatar = $result->data->avatar;
                $user->phone = $result->data->phone;
                $user->open_id = $result->data->open_id;
                $user->status = $result->data->status;
                $user->created_at = $result->data->created_at;
                $user->updated_at = $result->data->updated_at;
                if ($user->save()) {
                    return $user;
                }
                throw new \Exception($user->getErrorMsg());
            } else {
                throw new \Exception($result->msg);
            }
        } catch (\Exception $e) {
            throw $e;
        }
    }

    /**
     * 更新用户信息
     */
    public function updateUser($phone, $customerId, $openId, $avatar, $nickname)
    {
        $baseUrl = getenv("ISSURE_COUPON_API");
        $url = $baseUrl . "api/user/" . $phone;
        $data = ['phone' => $phone, 'customer_id' => $customerId, 'open_id' => $openId, 'avatar' => $avatar, 'nickname' => $nickname];
        try {
            $result = HttpRequestService::sendRequest($url, "PUT", $data);
            if ($result->code == 1) {
                $user = User::find()->where(['phone' => $phone])->one();
                if ($user == null) {
                    $user = new User();
                }
                $user->customer_id = $result->data->customer_id;
                $user->nickname = $result->data->nickname;
                $user->avatar = $result->data->avatar;
                $user->phone = $result->data->phone;
                $user->open_id = $result->data->open_id;
                $user->status = $result->data->status;
                $user->created_at = $result->data->created_at;
                $user->updated_at = $result->data->updated_at;
                if ($user->save()) {
                    return $user;
                }
                throw new \Exception($user->getErrorMsg());
            } else {
                throw new \Exception($result->msg);
            }
        } catch (\Exception $e) {
            throw $e;
        }
    }

}
